<?php

namespace app\admin\service;

use app\admin\validate\ArticleCateValidate;
use support\spark\exception\ApiException;
use support\spark\model\system\ArticleCate;

class ArticleCateService
{
    /**
     * 获取文章分类列表
     * @param $param
     * @return array
     */
    public function getList($param)
    {
        $name = $param['name'];
        $limit = $param['limit'];

        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }

        $articleCateModel = new ArticleCate();
        $list = $articleCateModel->getPaginateList($where, ['*'], ['id' => 'desc'], [], $limit);
        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加文章分类
     * @param $param
     */
    public function addArticleCate($param)
    {
        // 检验完整性
        $validate = new ArticleCateValidate();
        if (!$validate->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }

        $articleCateModel = new ArticleCate();
        $has = $articleCateModel->checkUnique([
            'name' => $param['name']
        ]);
        if (!empty($has)) {
            throw  new  ApiException('分类名已经存在', -1);
        }
        $param['create_time'] = now();
        $param['update_time'] = now();
        $articleCateModel->insertOne($param);
        return dataReturn(0, '添加成功');
    }

    /**
     * 编辑文章
     * @param $param
     */
    public function editArticle($param)
    {
        // 检验完整性
        $validate = new ArticleCateValidate();
        if (!$validate->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $articleCateModel = new ArticleCate();
        $where[] = ['id', '<>', $param['id']];
        $where[] = ['name', '=', $param['name']];
        $has = $articleCateModel->checkUnique($where);
        if (!empty($has)) {
            throw  new  ApiException('分类名已经存在', -1);
        }
        $articleCateModel->updateById($param, $param['id']);
        return dataReturn(0, '编辑成功');
    }
}